package com.gitee.feizns.dynamic.time;

import lombok.RequiredArgsConstructor;

import java.util.function.Supplier;

/**
 * 定时缓存
 * @author feizns
 * @since 2025/4/14
 */
@RequiredArgsConstructor
public class TimedCache<T> {

    /**
     * 定时值
     */
    private TimedValue<T> timedValue;

    /**
     * 定时值供应商
     */
    private final Supplier<TimedValue<T>> timedValueSupplier;

    /**
     * 获取
     * @return {@link T }
     */
    public T get() {
        if ( timedValue == null || timedValue.isExpired() )
            reset();
        return timedValue.get();
    }

    /**
     * 重置
     */
    public void reset() {
        timedValue = timedValueSupplier.get();
    }

    /**
     * {@link TimedCache}
     * @param timedValueSupplier 定时值供应商
     * @return {@link TimedCache }<{@link T }>
     */
    public static <T> TimedCache<T> of(Supplier<TimedValue<T>> timedValueSupplier) {
        return new TimedCache<>(timedValueSupplier);
    }

}
